package com.hxc.sercurity.hander;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 韩先楚
 */
//出理认证过程出现异常

/**
 * 当用户尝试访问受保护的资源，但未通过身份验证时，
 * Spring Security 会调用 AuthenticationEntryPoint 的 commence 方法。
 * 这个方法负责处理这种情况，通常是通过发送一个 HTTP 响应来指示用户需要进行身份验证。
 */
@Component
public class AuthEnterExceptionHander implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        httpServletResponse.getWriter().write("{\"code\":401,\"message\":\"认证失败\"}");

    }
}
